# frozen_string_literal: true

require 'spec_helper'

RSpec.describe VulnerabilityPolicy, feature_category: :vulnerability_management do
  describe '#rules' do
    let(:project) { create(:project) }
    let(:user) { create(:user) }
    let(:vulnerability) { create(:vulnerability, :with_finding, project: project) }

    subject { described_class.new(user, vulnerability) }

    context 'when the security_dashboard feature is enabled' do
      before do
        stub_licensed_features(security_dashboard: true)
      end

      context "when the current user is not a project member" do
        it { is_expected.to be_disallowed(:read_security_resource) }
        it { is_expected.to be_disallowed(:read_vulnerability) }
        it { is_expected.to be_disallowed(:create_note) }
        it { is_expected.to be_disallowed(:explain_vulnerability) }
      end

      context "when the current user has developer access to the vulnerability's project" do
        before do
          project.add_developer(user)
        end

        it { is_expected.to be_allowed(:read_security_resource) }
        it { is_expected.to be_allowed(:read_vulnerability) }
        it { is_expected.to be_allowed(:create_note) }

        context 'when on gitlab.com', :saas do
          let(:namespace) { create(:group_with_plan, plan: :ultimate_plan) }
          let(:project) { create(:project, namespace: namespace) }

          before do
            stub_ee_application_setting(should_check_namespace_plan: true)
            stub_licensed_features(ai_features: true, security_dashboard: true)

            namespace.update!(
              experiment_features_enabled: true,
              third_party_ai_features_enabled: true
            )
          end

          it { is_expected.to be_allowed(:explain_vulnerability) }
        end
      end

      context 'when the user is project member but does not have proper access' do
        before do
          project.add_guest(user)
        end

        it { is_expected.to be_disallowed(:create_note) }
      end
    end

    context 'when the security_dashboard feature is disabled' do
      before do
        stub_licensed_features(security_dashboard: false)

        project.add_developer(user)
      end

      it { is_expected.to be_disallowed(:read_security_resource) }
      it { is_expected.to be_disallowed(:read_vulnerability) }
      it { is_expected.to be_disallowed(:create_note) }
    end
  end
end
